package com.snopzyz.hello.databus.domain;

import com.snopzyz.hello.databus.enums.ColumnKeyType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Column {

    /**
     * 列号（第几列）
     */
    private Integer idx;

    /**
     * 键类型
     */
    private ColumnKeyType keyType;

    /**
     * 列名
     */
    private String colName;

    /**
     * 类型
     */
    private String dataType;

    /**
     * 库名
     */
    private String schema;

    /**
     * 表名
     */
    private String table;

    public static Column getColFrom (ResultSet resultSet) throws SQLException {
        String schema = resultSet.getString("TABLE_SCHEMA");
        String tableName = resultSet.getString("TABLE_NAME");
        String column = resultSet.getString("COLUMN_NAME");
        int idx = resultSet.getInt("ORDINAL_POSITION");
        String dataType = resultSet.getString("DATA_TYPE");
        String columnKey = resultSet.getString("COLUMN_KEY");
        if (column != null && idx >= 1) {
            // 查询结果 idx 从 1 开始的
            return new Column(idx - 1, ColumnKeyType.fromCode(columnKey), column, dataType, schema, tableName);
        }
        return null;
    }

    public static Map<String, Column> getTableFrom (ResultSet resultSet) throws SQLException {
        Map<String, Column> map = new HashMap<>(resultSet.getRow());
        while (resultSet.next()) {
            Column column = getColFrom(resultSet);
            if (column == null) {
                continue;
            }
            map.put(column.getColName(), column);
        }
        return map;
    }

}
